//
//  UIColor+JTExtension.m
//  百思不得姐
//
//  Created by Robin Zhang on 2017/3/1.
//  Copyright © 2017年 BeiJingWangDianJieTong. All rights reserved.
//

#import "UIColor+JTExtension.h"

@implementation UIColor (JTExtension)

/** 十六进制数转化为颜色(如 0x123456) */
// 1.十六进制数
+ (instancetype)jt_colorWithHex:(NSInteger)hexValue alpha:(CGFloat)alphaValue {
    
    return [self colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0
                        green:((float)((hexValue & 0xFF00) >> 8))/255.0
                         blue:((float)(hexValue & 0xFF))/255.0 alpha:alphaValue];
}

+ (instancetype)jt_colorWithHex:(NSInteger)hexValue {
    
    return [self jt_colorWithHex:hexValue alpha:1.0];
}

// 2.十六进制格式字符串
+ (instancetype)jt_colorWithHexString:(NSString *)hexValueString alpha:(CGFloat)alphaValue {
    
    if (!([hexValueString hasPrefix:@"0x"] || [hexValueString hasPrefix:@"0X"])) {
        
        hexValueString = [NSString stringWithFormat:@"0x%@", hexValueString];
    }
    
    NSInteger hexValue = strtoul([hexValueString UTF8String], 0, 0);
    
    JTLog(@"%ld", hexValue);
    
    return [self jt_colorWithHex:hexValue alpha:alphaValue];
}

+ (instancetype)jt_colorWithHexString:(NSString *)hexValueString {
    
    return [self jt_colorWithHexString:hexValueString alpha:1.0f];
}

/** 获取颜色的十六进制字符串 */
- (NSString *)jt_hexString {
    
    UIColor *color = [self copy];
    
    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
        
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[0]
                                green:components[0]
                                 blue:components[0]
                                alpha:components[1]];
    }
    
    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        
        return [NSString stringWithFormat:@"#FFFFFF"];
    }
    
    return [NSString stringWithFormat:@"#%x%x%x", (int)((CGColorGetComponents(color.CGColor))[0]*255.0),
            (int)((CGColorGetComponents(color.CGColor))[1]*255.0),
            (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];
}

@end
